<template>
  <div class="invitingMerchants">
    <div class="header">
      <van-nav-bar title="邀请商户" left-arrow @click-left="$router.go(-1)" />
    </div>
    <van-form ref="formRef">
      <van-cell title="联系电话：" v-if="isAdd">
        <template slot="default">
          <van-field
            v-model="formData.joinMobilePhone"
            placeholder="请输入联系电话"
            @blur="searchBusinessByPhone"
            @input="searchBusinessByPhone"
            :rules="[
              {
                required: false,
                message: '请输入正确的联系电话',
                validator: val => isInternalPhone(val)
              }
            ]"
            type="tel"
        /></template>
      </van-cell>

      <div
        class="business-phone-list"
        v-if="
          isAdd && formData.joinMobilePhone && businessPhoneList.length !== 0
        "
      >
        <div
          class="business-phone-list__item section-line"
          v-for="item in businessPhoneList"
          :key="item.id"
          :class="{ 'disable-busness-item': disableBusness(item) }"
        >
          <van-checkbox-group v-model="invitesArr">
            <div class="checkbox-group">
              <div class="checkbox">
                <van-checkbox
                  :disabled="disableBusness(item)"
                  :name="item.joinBusinessId || item.syncTmpMerchantId"
                  @click="onClickCheckbox(item)"
                ></van-checkbox>
              </div>
              <div class="info">
                <div class="info-item">商户名：{{ item.fullName }}</div>
                <div class="info-item">{{ item.mobilePhone }}</div>
                <div class="info-item">地址：{{ item.address }}</div>
              </div>
            </div>
            <template v-if="disableBusness(item)">
              <div class="tips" v-if="item.inCooperate || item.invited">
                注:{{ disableBusnessErrorText.isInCooperateText }}
              </div>
              <div class="tips" v-if="item.inCooperateSelf">
                注:{{ disableBusnessErrorText.isInCooperateSelfText }}
              </div>
              <div class="tips" v-if="item.messageTips">
                注:{{ item.messageTips }}，不可邀请
              </div>
              <!--              <div class="tips" v-if="item.differentDept">-->
              <!--                注:{{ disableBusnessErrorText.isDifferentDeptText }}-->
              <!--              </div>-->
              <!--              <div class="tips" v-if="!item.differentDept">-->
              <!--                <div v-if="item.differentChannel" class="tip">-->
              <!--                  注:{{ disableBusnessErrorText.isDifferentChannelText }}-->
              <!--                </div>-->
              <!--              </div>-->
              <div class="tips" v-if="item.invitedSelf">
                注:{{ disableBusnessErrorText.isInvitedSelfText }}
              </div>
            </template>
          </van-checkbox-group>
        </div>
      </div>

      <div class="joinBusinessInfo" v-if="!isAdd">
        <div
          class="joinBusinessInfo__item section-line"
          :class="{ 'disable-busness-item': disableBusness(formData) }"
        >
          <div class="checkbox-group">
            <div class="info">
              <div class="info-item">
                <span>{{ formData.joinBusinessName }}</span>
                <span class="joinMobilePhone">{{
                  formData.joinMobilePhone
                }}</span>
              </div>
              <div class="info-item">地址：{{ formData.joinAddress }}</div>
            </div>
          </div>
        </div>
      </div>

      <!--      <div  class="joinBusinessInfo">-->
      <!--        <div class="info-item">商户名：{{ formData.joinBusinessName }}</div>-->
      <!--        <div class="info-item">联系电话：{{ formData.joinMobilePhone }}</div>-->
      <!--        <div class="info-item">地址：{{ formData.joinAddress }}</div>-->
      <!--      </div>-->

      <van-cell title="*出资方：">
        <template slot="default">
          <van-radio-group
            v-model="formData.financingParty"
            direction="horizontal"
          >
            <van-radio :name="2">合作商户</van-radio>
            <van-radio :name="1">本商户</van-radio>
          </van-radio-group>
        </template>
      </van-cell>

      <van-cell title="*是否需要同意：" v-if="formData.financingParty === 1">
        <template slot="default">
          <van-radio-group v-model="formData.needAgree" direction="horizontal">
            <van-radio :name="true">是</van-radio>
            <van-radio :name="false">否</van-radio>
          </van-radio-group>
        </template>
      </van-cell>

      <section>
        <van-cell title="*优惠折扣：">
          <template slot="default">
            <div class="flex-align-center">
              <van-field
                type="number"
                v-model="formData.discount"
                placeholder="请输入优惠折扣"
                :rules="[
                  {
                    trigger: 'onBlur',
                    message: '只可输入1位小数正数，可输入范围0～9.9',
                    validator: val =>
                      Number(val) && 9.9 >= Number(val) && Number(val) >= 0
                  }
                ]"
              />折
            </div>
          </template>
        </van-cell>
        <span class="tips">注：只可输入1位小数正数，可输入范围0～9.9</span>
      </section>

      <section>
        <van-cell title="*抽佣比例：">
          <template slot="default">
            <div class="flex-align-center">
              <van-field
                :disabled="rakeRateDisable"
                type="number"
                v-model="formData.rakeRate"
                placeholder="请输入抽佣比例"
                :rules="[
                  {
                    trigger: 'onBlur',
                    message: '可输入比例范围0～19正整数',
                    validator: val =>
                      Number(val) % 1 === 0 &&
                      19 >= Number(val) &&
                      Number(val) >= 0
                  }
                ]"
              />%
            </div>
          </template>
        </van-cell>
        <span class="tips">注：可输入比例范围0～19正整数</span>
      </section>

      <section class="section-line">
        <van-cell title="*积分奖励：" :border="false"> </van-cell>
        <div style="padding: 0 20px">
          <div>用户实付：</div>
          <div class="flex-align-center van-cell__value">
            <van-field
              type="number"
              style="width: 100px"
              v-model="formData.rewardCoefficient"
              placeholder="请输入积分奖励"
              :rules="[
                {
                  trigger: 'onBlur',
                  message: '请输入0～9999,不可输入小数，输入0表示不奖励积分',
                  validator: val =>
                    Number(val) &&
                    Number(val) % 1 === 0 &&
                    9999 >= Number(val) &&
                    Number(val) >= 0
                }
              ]"
            />
            <div>元奖励1个积分，未满1元不奖励</div>
          </div>
        </div>
        <van-radio-group
          style="margin-top: 5px;margin-left: 20px;"
          v-model="formData.recyclePoints"
        >
          <van-radio :name="false">订单售后不回收奖励积分</van-radio>
          <van-radio :name="true" style="margin-top: 5px;"
            >订单售后回收奖励积分</van-radio
          >
        </van-radio-group>
        <span class="tips"
          >注：可输入0～9999,不可输入小数，输入0表示不奖励积分</span
        >
      </section>

      <section class="section-line">
        <van-cell title="*积分抵扣比例：" :border="false"> </van-cell>
        <div style="padding: 0 20px">
          <div>按订单金额：</div>
          <div class="flex-align-center van-cell__value">
            <van-field
              type="number"
              style="width: 100px"
              v-model="formData.deductionRatio"
              placeholder="请输入积分奖励"
              :rules="[
                {
                  trigger: 'onBlur',
                  message: '请输入0～99,不可输入小数，输入0表示不可用积分抵扣',
                  validator: val =>
                    Number(val) &&
                    Number(val) % 1 === 0 &&
                    99 >= Number(val) &&
                    Number(val) >= 0
                }
              ]"
            /><span>%抵扣，每10个积分抵扣1元</span>
          </div>
        </div>
        <span class="tips"
          >注：可输入0～99,不可输入小数,输入0表示不可用积分抵扣</span
        >
      </section>
      <div class="footer">
        <van-button
          class="van-button-edit"
          native-type="submit"
          @click="onSubmit"
          >{{ isAdd ? "发起邀请" : "保存" }}</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  searchBusinessByPhon,
  inviteBusiness,
  getBusinessDetail,
  getChannelAccountBalanc,
  modifyRecord
} from "@/api/flow/index";
import { Dialog } from "vant";
const disableBusnessErrorText = {
  isInCooperateText: "已跟其他商户合作",
  isInvitedText: "已跟其他商户合作",
  hasBindSubsidyText: "已跟其他商户合作",
  isInCooperateSelfText: "跟本商户合作中",
  isDifferentDeptText: "机构不一致",
  // isDifferentChannelText: "当前商户下门店支付渠道不一致，不可邀请",
  isDifferentChannelText: "支付渠道不一样",
  isInvitedSelfText: "被本商户邀请了超级会员"
};
const isInternalPhone = str => /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(str); // 国内手机 包含大陆/台湾/香港/澳门
export default {
  name: "index",
  data() {
    return {
      disableBusnessErrorText,
      isInternalPhone,
      invitesArr: [],
      formData: {
        deductionRatio: 0,
        discount: 0,
        financingParty: 2, //出资方：1 邀请者、2 参与者
        invites: [], //商户的ids
        joinMobilePhone: "",
        needAgree: true,
        rakeRate: 0,
        recyclePoints: false,
        rewardCoefficient: 0
      },
      businessPhoneList: [],
      isAdd: null
    };
  },
  created() {
    //true是新增，false是编辑
    this.isAdd =
      this.$route?.query?.isAdd === undefined ||
      this.$route?.query?.isAdd === null
        ? null
        : this.$route?.query?.isAdd === true ||
          this.$route?.query?.isAdd === "true";
    if (this.isAdd !== null && this.isAdd !== undefined && !this.isAdd) {
      const info = JSON.parse(localStorage.getItem("invitingMerchantsInfo"));
      if (info) {
        console.log(">>>>", info);
        this.formData = info;
      }
    }
  },
  computed: {
    flowQueryData() {
      return this.$store.state.flow.flowQueryData;
    },

    rakeRateDisable() {
      return this.formData.financingParty === 1 && !this.formData.needAgree;
    }
  },
  watch: {
    rakeRateDisable(val) {
      if (val) {
        this.formData.rakeRate = 0;
      }
    }
  },
  methods: {
    onClickCheckbox({ joinBusinessId, syncTmpMerchantId, hasBindSubsidy }) {
      // hasBindSubsidy
      if (
        this.formData.financingParty === 1 ||
        this.formData.deductionRatio > 0
      ) {
        if (hasBindSubsidy) {
          Dialog({
            message:
              "当前邀请商户已与其他商户绑定补贴关系，不可选择出资方为“本商户",
            title: "提示"
          });
        }
      }
      let obj = {};
      if (joinBusinessId) {
        obj.joinBusinessId = joinBusinessId;
      }
      if (syncTmpMerchantId) {
        obj.syncTmpMerchantId = syncTmpMerchantId;
      }
      obj.hasBindSubsidy = hasBindSubsidy;
      //当此时是新增的时候
      if (this.invitesArr.length > this.formData.invites.length) {
        this.formData.invites.push(obj);
      } else if (this.invitesArr.length < this.formData.invites.length) {
        //当此时是减少的时候
        const tempInvites = [];
        this.invitesArr.forEach(item => {
          const tempItem = this.formData.invites.filter(
            v => item === v.joinBusinessId || item === v.syncTmpMerchantId
          );
          tempInvites.push(tempItem[0]);
        });
        this.formData.invites = tempInvites;
      }
    },
    async onSubmit() {
      let { deductionRatio } = this.formData;
      if (deductionRatio > 0) {
        getBusinessDetail({
          merchantId: this.flowQueryData.merchantId
        }).then(res => {
          const {
            code,
            data: { marketingAccount }
          } = res.data;
          if (code === 0) {
            if (!marketingAccount) {
              // 点开通后，需要查询接口商户邮箱是否设置，设置了立即开通，未设置提示
              Dialog({
                message: "请在电脑端商户后台绑定营销户账户号",
                title: "提示"
              });
            } else {
              getChannelAccountBalanc({
                merchantId: this.flowQueryData.merchantId
              }).then(async res => {
                const { code, data } = res.data;
                if (code === 0) {
                  if (!data || data === 0) {
                    await Dialog({
                      message: "当前补贴金额不足，请在电脑上操作充值",
                      title: "提示"
                    });
                  } else {
                    await this.submitInviting();
                  }
                }
              });
            }
          }
        });
      } else {
        await this.submitInviting();
      }
    },
    async submitInviting() {
      let {
        deductionRatio,
        discount,
        financingParty,
        invites,
        joinMobilePhone,
        needAgree,
        rakeRate,
        recyclePoints,
        rewardCoefficient
      } = this.formData;
      let hasBindSubsidy = false;
      invites.forEach(v => {
        if (v.hasBindSubsidy) {
          hasBindSubsidy = true;
        }
      });

      console.log(
        "提交的时候",
        hasBindSubsidy,
        "financingParty：",
        financingParty,
        "deductionRatio：",
        deductionRatio
      );

      if (financingParty === 1 || deductionRatio > 0) {
        if (hasBindSubsidy) {
          Dialog({
            message:
              "当前邀请商户已与其他商户绑定补贴关系，不可选择出资方为“本商户",
            title: "提示"
          });
        }
      }

      // if (hasBindSubsidy) {
      //   Dialog({
      //     message:
      //       "当前邀请商户已与其他商户绑定补贴关系，不可选择出资方为“本商户",
      //     title: "提示"
      //   });
      //   return;
      // }
      const apis = this.isAdd ? inviteBusiness : modifyRecord;
      const { data } = await apis({
        ...this.formData,
        merchantId: this.flowQueryData.merchantId,
        deductionRatio: Number(deductionRatio),
        discount: Number(discount),
        rakeRate: Number(rakeRate),
        rewardCoefficient: Number(rewardCoefficient)
      });
      const { code, msg } = data;
      if (code === 0) {
        this.$toast.success("成功!");
        setTimeout(() => {
          this.$router.go(-1);
        }, 500);
      } else {
        this.$toast.fail(msg);
      }
    },
    disableBusness({
      inCooperate,
      invited,
      inCooperateSelf,
      differentDept,
      differentChannel,
      invitedSelf
    }) {
      return (
        inCooperate ||
        invited ||
        inCooperateSelf ||
        differentChannel ||
        differentDept ||
        invitedSelf
      );
    },
    async searchBusinessByPhone() {
      if (!this.isInternalPhone(this.formData.joinMobilePhone)) return;
      const res = await searchBusinessByPhon({
        phone: this.formData.joinMobilePhone,
        merchantId: this.flowQueryData.merchantId
      });
      const { code, data } = res.data;
      this.businessPhoneList = data;
      console.log(
        "hasBindSubsidy",
        data.filter(v => v.hasBindSubsidy)
      );
    }
  }
};
</script>

<style scoped lang="less">
.van-cell__value {
  color: black;
  flex: 1;
  font-size: 0.8rem;
}
/deep/.van-field__value {
  border: 1px solid #cacaca;
}
/deep/.van-field__control {
  text-indent: 18px;
}
.van-cell {
  position: relative;
}
/deep/.van-radio__label {
  font-size: 0.85rem;
}
.van-cell__title {
  display: flex;
  align-items: center;
  flex: none;
  font-size: 1rem;
}
.van-form {
  margin-bottom: 120px;
}
.tips {
  margin-left: 40px;
  margin-top: 5px;
  font-size: 0.8rem;
  font-family: PingFang SC;
  font-weight: 500;
  color: red;
  line-height: 54px;
  opacity: 0.7;
  padding: 0 15px;
}
.section-line {
  position: relative;
  font-size: 0.95rem;
  &::after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    right: 16px;
    bottom: -10px;
    left: 16px;
    border-bottom: 1px solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
}

.invitingMerchants {
  overflow: scroll;
  .flex-align-center {
    display: flex;
    align-items: center;
  }
  .footer {
    width: 100vw;
    position: fixed;
    bottom: 0;
    .van-button {
      width: 100%;
    }
  }

  .joinBusinessInfo {
    font-size: 1rem;
    width: 95%;
    margin: 0 auto;
    border-radius: 18px;
    background-color: whitesmoke;
    padding: 0 15px;
    &__item {
      margin: 5px auto;
    }
    .checkbox-group {
      display: flex;
      align-items: center;
      .checkbox {
        flex: 0.2;
      }
      .info {
        flex: 2;
        &-item {
          margin: 5px 0;
          display: flex;
          padding: 10px 5px;
          span {
            flex: 1;
          }
          .joinMobilePhone {
            text-align: right;
          }
        }
      }
    }
  }
  .business-phone-list {
    padding: 0 15px;
    height: 500px;
    overflow: hidden;
    overflow-y: scroll;
    font-size: 1rem;
    .disable-busness-item {
      background-color: whitesmoke;
    }
    &__item {
      margin: 5px auto;
    }
    .checkbox-group {
      display: flex;
      align-items: center;
      .checkbox {
        flex: 0.2;
      }
      .info {
        flex: 2;
        &-item {
          margin: 5px 0;
        }
      }
    }
  }
}
.van-button-edit {
  color: white;
  background-color: #ffb72f;
}
</style>
